package cn.javacart.jopencart.library;

public class PaginationService {
	
	/**
	 * 总数
	 */
	public long total = 0;
	/**
	 * 当前页
	 */
	public int page = 1;
	/**
	 * 页面大小
	 */
	public int limit = 20;
	/**
	 * 显示的连接数
	 */
	public int numLinks = 8;
	/**
	 * url
	 */
	public String url = "";
	/**
	 * 第一页
	 */
	public String textFirst = "|&lt;";
	/**
	 * 最后一页
	 */
	public String textLast = "&gt;|";
	/**
	 * 下一页
	 */
	public String textNext = "&gt;";
	/**
	 * 上一页
	 */
	public String textPrev = "&lt;";
	
	/**
	 * 
	 * @return
	 */
	public String render(){
		StringBuilder output = new StringBuilder("<ul class=\"pagination\">");
		if(page < 1){
			page = 1;
		}
		if(limit < 1){
			limit = 1;
		}
		int numPages = (int)Math.ceil((double)total/(double)limit);
		int start = 0;
		int end = 0;
		url = url.replace("%7Bpage%7D", "{page}");
		if(page>1){
			output.append("<li><a href=\"").append(url.replace("&page={page}", "")).append("\">").append(textFirst).append("</a></li>");		
			if(page - 1 == 1){
				output.append("<li><a href=\"").append(url.replace("&page={page}", "")).append("\">").append(textPrev).append("</a></li>");
			} else {
				output.append("<li><a href=\"").append(url.replace("{page}", ""+(page-1))).append("\">").append(textPrev).append("</a></li>");		
			}
		}
		if(numPages>1){
			if(numPages <= numLinks){
				start = 1;
				end = numPages;
			}
			else{
				start = page -(int) Math.floor((double)numLinks / (double)2);
				end = page + (int) Math.floor((double)numLinks / (double)2);
				if(start<1){
					end = end + Math.abs(start) + 1;
					start = 1;
				}
				if(end>numPages){
					start = start - (end-numPages);
					end = numPages;
				}
				
			}
			for (int i = start; i <= end; i++) {
				if(page == i){
					output.append("<li class=\"active\"><span>").append(i).append("</span></li>");
				}else {
					if(i == 1){
						output.append("<li><a href=\"").append(url.replace("&page={page}", "")).append("\">").append(i).append("</a></li>");
					}else{
						output.append("<li><a href=\"").append(url.replace("{page}", ""+i)).append("\">").append(i).append("</a></li>");
					}
					
				}
			}
		}
		if(page<numPages){
			output.append("<li><a href=\"").append(url.replace("{page}", ""+(1+page))).append("\">").append(textNext).append("</a></li>");
			output.append("<li><a href=\"").append(url.replace("{page}", ""+numPages)).append("\">").append(textLast).append("</a></li>");
		}
		output.append("</ul>");
		if(numPages > 1){
			return output.toString();
		}
		return "";
	}
	
	
}
